package com.cskaoyan.service.wx.Shippingaddress;

import com.cskaoyan.dao.wx.adress.WXAddressDao;
import com.cskaoyan.model.realm.WxLoginUserData;
import com.cskaoyan.model.wx.wxadressbean.bo.WXAddressSaveBo;
import com.cskaoyan.model.wx.wxadressbean.vo.WXAddressDetailVo;
import com.cskaoyan.model.wx.wxadressbean.vo.WXAdressList;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: XM
 * @date: 2022/1/10 20:19
 */
@Component
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    WXAddressDao wxAddressDao;
    @Override
    public WXAdressList addressList() {
        Integer i = wxAddressDao.selectCount();
        List<WXAdressList.ListBean> listBeans = wxAddressDao.selectAddressAll();
        return new WXAdressList(i,1,i,1,listBeans);
    }

    @Override
    public WXAddressDetailVo getAdressDetail(Integer id) {
        WXAddressDetailVo wxAddressDetailVo = wxAddressDao.selectAddressDetail(id);
        return wxAddressDetailVo;
    }

    @Override
    public Integer addressSaveMsg(@RequestBody WXAddressSaveBo addressSaveBo) {
       //获取id
        WxLoginUserData principal = (WxLoginUserData) SecurityUtils.getSubject().getPrincipal();
        Integer userId = principal.getId();

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
        String format = dateFormat.format(date);
        addressSaveBo.setUpdateTime(format);

        System.out.println(addressSaveBo.toString());
        System.out.println("---------------------------");
        //判断地址表中是否有数据
        Integer count=wxAddressDao.selectAddressData(addressSaveBo.getId());

        //如果返回值为1，修改地址表信息
        //如果返回值为0，新增地址表信息
        if(count==1){
            //如果修改为默认地址，其他default都为0
            if(addressSaveBo.getIsDefault()==1){
              wxAddressDao.updateAddressDefault();
            }
            Integer number = wxAddressDao.updateAdress(addressSaveBo);
            return addressSaveBo.getId();
        }else if(count==0){
            //如果修改为默认地址，其他default都为0
            if(addressSaveBo.getIsDefault()==1){
                wxAddressDao.updateAddressDefault();
            }
            Integer id=wxAddressDao.insertAddress(addressSaveBo,userId);
            return addressSaveBo.getId();
        }
         return  0;

    }

    @Override
    public Integer addressDelete(Integer id) {
        Integer i = wxAddressDao.deleteAdress(id);
        return i;
    }
}